﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace WinHBM.Utils
{
    class UtilUpdate
    {

        private const string updateUrl = "http://hbm.jyq365.com/download/ytj/update.xml";//升级配置XML文件地址  
        public string newVerson="1.0.0.0";
        private static UtilUpdate utilUpdate;

        public static UtilUpdate getInstance() {
            if (utilUpdate == null) {
                utilUpdate = new UtilUpdate();
            }
            return utilUpdate;
        }


        private UtilUpdate() { }


        /**
         * 检测网络连接
         */ 
        public bool checkNetWork() {
            try
            {
                System.Net.WebRequest myRequest = System.Net.WebRequest.Create("http://www.baidu.com");
                System.Net.WebResponse myResponse = myRequest.GetResponse();
            }
            catch (System.Net.WebException)
            {
                return false;
            }
            return true;

    }

        /**
         * 检查更新
         */ 
        public bool checkNeedUpdate()
        {
            bool needUpdate = false;
            try
            {
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(updateUrl);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);
                XmlNode list = xmlDoc.SelectSingleNode("Update");
                newVerson = list.SelectSingleNode("Soft").SelectSingleNode("Version").InnerText;
                Version ver = new Version(newVerson);
                Version verson = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                int result = verson.CompareTo(ver); //版本号比较
                if (result >= 0)
                    needUpdate = false;
                else
                    needUpdate = true;
            }
            catch (Exception ex)
            {
                throw new Exception("更新出现错误，请确认网络连接无误后重试！");
            }

            return needUpdate;
        }

        /**
         * 启动更新
         */ 
        public void startUpdate() {
            try
            {
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "Update.exe";
                process.StartInfo = startInfo;
                process.Start();
                //System.Windows.Forms.Application.Exit();
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                throw new Exception("更新程序启动失败");
            }

        }

    }
}
